﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Configuration;

namespace DNA.Mvc
{
    public class ScoredEventObserver : EventObserver
    {
        private IEventScoreRepository eventRepository;
        private bool enableScoring = false;

        public ScoredEventObserver(IEventScoreRepository repository)
        {
            eventRepository = repository;
            var config = WebConfigurationManager.OpenWebConfiguration("~/web.config");
            if (config.AppSettings.Settings["enableScoring"] != null)
                enableScoring = bool.Parse(config.AppSettings.Settings["enableScoring"].Value);
        }

        protected override void ProcessEvent(EventBase e)
        {
            if (enableScoring)
            {
                if ((e.HttpContext != null) && (e.HttpContext.Request.IsAuthenticated) && (e.HttpContext.User != null) && (e.HttpContext.User.Identity != null))
                {
                    var score = eventRepository.Find(e.Name);
                    if (score != null)
                    {
                        var profile = e.HttpContext.Profile;
                        if (profile["Points"] != null)
                            profile["Points"] = (int)profile["Points"] + score.Points;
                        else
                            profile["Points"] = score.Points;
                        profile.Save();
                    }
                }
            }
        }
    }
}
